<template>
  <div ref="editor"></div>
</template>

<script>
import E from 'wangeditor'
import { marked } from 'marked'
import he from 'he'

export default {
  name: 'WangEditor',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      editor: null,
      skipUpdate: false
    }
  },
  mounted() {
    this.editor = new E(this.$refs.editor)
    
    this.editor.config.onchange = (html) => {
      this.onEditorChange(html)
    }

    // 关闭自动修正
    this.editor.config.pasteFilterStyle = false
    this.editor.config.pasteTextHandle = (content) => content

    this.editor.create()
    this.setInitialContent()
  },
  methods: {
    setInitialContent() {
      try {
        const unescaped = he.decode(this.value)
        const html = marked.parse(unescaped)
        this.editor.txt.html(html)
      } catch (e) {
        console.error('Error parsing content:', e)
        this.editor.txt.html(this.value)
      }
    },
    onEditorChange(html) {
      this.skipUpdate = true
      this.$emit('input', html)
    }
  },
  watch: {
    value(newVal) {
     
      if (this.skipUpdate) {
        this.skipUpdate = false
        return
      }
      try {
        this.$nextTick(()=>{
          const unescaped = he.decode(newVal)
          const html = marked.parse(unescaped)
          this.editor.txt.html(html)
        })
      } catch (e) {
        console.error('Error updating content:', e)
        this.editor.txt.html(newVal)
      }
    }
  },
  beforeDestroy() {
    this.editor.destroy()
  }
}
</script>

<style  scoped>
.w-e-text-container {
  height: 300px !important;
}

</style>

<style lang="scss">
///Knowledge/Knowledge路由添加企业智库弹窗的内容编辑框
.night{
  .w-e-text{
    background: #2a2d3c !important;
  }
}

</style>